<template>
    <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="onChange"
            :before-upload="beforeCheck"
    >
        <el-image v-if="upload.imageUrl" :src="upload.imageUrl" class="avatar" :style="upload.style"></el-image>
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
</template>
<script lang="ts" setup>
import {onMounted, reactive} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {defineEmits} from "vue";

const emit = defineEmits(["uploadSuccess"]);
const upload = reactive({
    imageUrl: '',
    style: {
        width: '',
        height: '',
        lineHeight: ''
    }
})

const props = defineProps({
    width: {
        type: String
    },
    height: {
        type: String
    }
});

const onChange = (file) => {
    if (file) {
        upload.imageUrl = URL.createObjectURL(file.raw);
        const reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = function (e) {
            emit('uploadSuccess', e.target.result);
        };
    }
}

const beforeCheck = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

onMounted(() => {
    upload.style.width = props.width ? props.width : '178px';
    upload.style.height = props.height ? props.height : '178px';
    upload.style.lineHeight = props.height ? props.height : '178px';

})
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
